﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Net;
using AjaxControlToolkit;
using System.Xml;


namespace publico
{
    public class PUB_FUNCOES : System.Web.UI.Page
    {

        #region Senhas
		 
	
        

        public static string CriptografarSenha(string senha)
        {
            //Declarations
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(senha);
            encodedBytes = md5.ComputeHash(originalBytes);

            //Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes).Replace("-", "");
        }

        public static string CriarSenhaAleatoria()
        {

            string senhaGerada = "";

            int x;

            string[] senhaGeradaTemp = new string[8];
            string[] caracteresMaisculos = new string[24];
            string[] caracteresMinusculos = new string[24];
            string[] caracteresEspeciais = new string[7];
            int[] numeros = new int[10];

            caracteresMaisculos = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
            caracteresMinusculos = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y" };
            caracteresEspeciais = new string[] { "@", "!", "#", "$", "^", "&", "+" };
            numeros = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            Random random = new Random();

            //Seleciona 1 caracter maisculo e outro especial
            for (x = 0; x < 1; x++)
            {
                int i = Convert.ToInt32(random.Next(0, 24));

                senhaGeradaTemp[x] = caracteresMaisculos[i].ToString();

                int y = Convert.ToInt32(random.Next(0, 7));

                senhaGeradaTemp[x + 1] += caracteresEspeciais[y].ToString();
            }

            //Seleciona 2 numeros
            for (x = 2; x < 4; x++)
            {
                int i = Convert.ToInt32(random.Next(0, 10));

                senhaGeradaTemp[x] += numeros[i].ToString();
            }


            //Seleciona o restante de caracteres minusculos
            for (x = 4; x < 8; x++)
            {
                int i = Convert.ToInt32(random.Next(0, 24));

                senhaGeradaTemp[x] += caracteresMinusculos[i].ToString();
            }


            //Pega a Senha gerada temporaria e realiza novo random
            //Seleciona o restante de caracteres minusculos
            for (x = 0; x < 8; x++)
            {
                int i = Convert.ToInt32(random.Next(0, 8));

                if (senhaGeradaTemp[i] != "")
                {
                    senhaGerada += senhaGeradaTemp[i].ToString();

                    senhaGeradaTemp[i] = "";
                }
                else
                    x--;
            }

            //retorna Senha gerada
            return senhaGerada;
        }
        
        #endregion

        #region Download
        public static void DownloadSincronizado(Uri url, string arquivo_destino)
        {
            WebClient wb = new WebClient();
            wb.DownloadFile(url, arquivo_destino);
        }

        public static void DownloadSincronizado(string url, string arquivo_destino)
        {
            WebClient wb = new WebClient();
            wb.DownloadFile(url, arquivo_destino);
        }
        
        public static void DownloadAssincrono(Uri url, string arquivo_destino)
        {
            WebClient wb = new WebClient();
            wb.DownloadFileAsync(url, arquivo_destino);
        }	    

        #endregion

        #region Atributo Arquivo
		 
        public static bool ArquivoEstaApenasLeitura(string arquivo)
        {
            bool isReadOnly = ((File.GetAttributes(arquivo) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

            return isReadOnly;
        }

        public static bool ArquivoEstaOculto(string arquivo)
        {
            bool isHidden = ((File.GetAttributes(arquivo) & FileAttributes.Hidden) == FileAttributes.Hidden);

            return isHidden;
        }

        public static FileAttributes ArquivoAtributo(string arquivo)
        {
            // get file attributes
            FileAttributes fileAttributes = File.GetAttributes(arquivo);
            return fileAttributes;
        }

        public static bool ArquivoCopiar(string arquivo_origem, string arquivo_destino)
        {
            try 
	        {
                FileInfo fi = new FileInfo(arquivo_origem);
                fi.CopyTo(arquivo_destino);

                return true;
		
	        }
	        catch (Exception)
	        {
		
		        return  false;
	        }


        }

        public static Dictionary<string,string> Drive()
        {
            DriveInfo[] drives = DriveInfo.GetDrives();

            Dictionary<string, string> d = new Dictionary<string, string>();
            foreach (DriveInfo drive in drives)
            {
                d.Add(drive.Name.ToString(),drive.DriveType.ToString());
            }

            return d;
        }




        #endregion

        #region Diretorio e Arquivo


        public static FileStream AbrirArquivo(String file, FileMode mode)
        {
            FileStream fs = new FileStream(file, mode);

            return fs;
        }
         

        public static void FecharArquivo(FileStream file)
        {
            file.Close();
        }

        /// <summary>
        /// Exclui um arquivo caso exista
        /// </summary>
        /// <param name="arquivo"></param>
        /// <returns></returns>
        public static Boolean ExcluirArquivo(String file)
        {

            if (ExisteArquivo(file))
            {

                File.Delete(file);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Verifica se existe o arquivo
        /// </summary>
        /// <param name="arquivo"></param>
        /// <returns></returns>
        public static Boolean ExisteArquivo(String _file)
        {
            try
            {
                FileInfo fi = new FileInfo(_file);
                if (fi.Exists)
                {

                    return true;
                }

                return false;

            }
            catch (Exception)
            {

                throw;
            }



        }

        public static bool CriarArquivo(string _file)
        {
            try
            {
                File.Create(_file);

                return true;
            }
            catch (Exception)
            {

                return false;
            }
            
        }

        public static bool SalvarXml(string _file, string _conteudo)
        {
            try
            {

                if (ExisteArquivo(_file))
                {
                    ExcluirArquivo(_file);
                }

                StreamWriter sw = new StreamWriter(_file);
                sw.Write(_conteudo);
                sw.Close();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
            

        }

        public static bool SalvarTxt(string _file, string _conteudo)
        {
            try
            {

                if (ExisteArquivo(_file))
                {
                    ExcluirArquivo(_file);
                }

                StreamWriter sw = new StreamWriter(_file);
                sw.Write(_conteudo);
                sw.Close();
                return true;
            }
            catch (Exception)
            {
                
                throw;
            }
        }


        public static XmlDocument LerDocumentoXml(string _file)
        {
            XmlDocument xdoc = new XmlDocument();

            xdoc.LoadXml(_file);
            return xdoc;

        }


        public static XmlElement LerElementoXml(XmlDocument xdoc, string elemento)
        {            
            return xdoc.DocumentElement[elemento];
            
        }

        public static XmlAttribute LerAtributoXml(XmlElement xelemento, string atributo)
        {
            
            return xelemento.Attributes[atributo];
        }





        public static void LerXml(string file)
        {
            XmlTextReader reader = new XmlTextReader(file);
            reader.WhitespaceHandling = WhitespaceHandling.None;

            // Parse the file and display each of the nodes. 
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.Write("<{0}>", reader.Name);
                        break;
                    case XmlNodeType.Text:
                        Console.Write(reader.Value);
                        break;
                    case XmlNodeType.CDATA:
                        Console.Write("<![CDATA[{0}]]>", reader.Value);
                        break;
                    case XmlNodeType.ProcessingInstruction:
                        Console.Write("<?{0} {1}?>", reader.Name, reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        Console.Write("<!--{0}-->", reader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                        Console.Write("<?xml version='1.0'?>");
                        break;
                    case XmlNodeType.Document:
                        break;
                    case XmlNodeType.DocumentType:
                        Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
                        break;
                    case XmlNodeType.EntityReference:
                        Console.Write(reader.Name);
                        break;
                    case XmlNodeType.EndElement:
                        Console.Write("</{0}>", reader.Name);
                        break;
                }
            }

            reader.Close();

        }



        public static string LerTxt(string file)
        {
            StreamReader sr = new StreamReader(file);
            return sr.ReadToEnd();
        }



        public static bool SalvarTxt(string file, string conteudo, bool adicionar)
        {
            try
            {
                StreamWriter sw = new StreamWriter(file, true);

                if (adicionar)
                {
                    sw.WriteLine(conteudo);
                }
                else
                {
                    sw.Write(conteudo);
                }
                
                sw.Close();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }



        /// <summary>
        /// Verifica se existe o diretorio
        /// </summary>
        /// <param name="diretorio"></param>
        /// <returns></returns>
        public static Boolean ExisteDiretorio(String dir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(dir);
                if (di.Exists)
                {
                    return true;
                }
                return false;

            }
            catch (Exception)
            {

                throw;
            }



        }
        /// <summary>
        /// Cria um novo diretorio
        /// </summary>
        /// <param name="diretorio"></param>
        public static DirectoryInfo CriarDiretorio(String dir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(dir);
                if (!ExisteDiretorio(dir))
                {

                    Directory.CreateDirectory(dir);
                }

                return di;

            }
            catch (Exception)
            {

                throw;
            }



        }

        public static FileInfo InfoArquivo(String file)
        {            
           
            FileInfo fi = new FileInfo(file);

            return fi;
        }

        /// <summary>
        /// Exclui diretorio
        /// </summary>
        /// <param name="diretorio"></param>
        public static void ExcluirDiretorio(String dir)
        {
            try
            {
                if (ExisteDiretorio(dir))
                {
                    Directory.Delete(dir, true);

                }

            }
            catch (Exception)
            {

                throw;
            }

        }
      

        public void ListaDiretorioTreeView(String path, TreeNode treeNode)
        {

            if (!string.IsNullOrEmpty(path))
            {

                foreach (string directoryPath in System.IO.Directory.GetDirectories(path))
                {

                    System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(directoryPath);

                    TreeNode subNode = new TreeNode(directory.Name, directory.FullName);

                    subNode.ShowCheckBox = true;

                    subNode.CollapseAll();

                    treeNode.ChildNodes.Add(subNode);

                    // bind sub directories

                    ListaDiretorioTreeView(directoryPath, subNode);

                }

            }

        }


        #endregion

        #region Validação  CNPJ/CPF/EMAIL

        public static bool ValidaCNPJ(string cnpj)
        {
            int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
            int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
            int soma;
            int resto;
            string digito;
            string tempCnpj;

            cnpj = cnpj.Trim();
            cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", "");

            if (cnpj.Length != 14)
                return false;

            tempCnpj = cnpj.Substring(0, 12);

            soma = 0;
            for (int i = 0; i < 12; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];

            resto = (soma % 11);
            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = resto.ToString();

            tempCnpj = tempCnpj + digito;
            soma = 0;
            for (int i = 0; i < 13; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];

            resto = (soma % 11);
            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = digito + resto.ToString();

            if (cnpj.Substring(12,2) == digito)
            {
                return true;
            }
            else
            {
                return false;
            }
            //return cnpj.EndsWith(digito);
        }

        public static bool ValidaCPF(string vrCPF)
        {

            string valor = vrCPF.Replace(".", "");

            valor = valor.Replace("-", "");



            if (valor.Length != 11)

                return false;



            bool igual = true;

            for (int i = 1; i < 11 && igual; i++)

                if (valor[i] != valor[0])

                    igual = false;



            if (igual || valor == "12345678909")

                return false;



            int[] numeros = new int[11];



            for (int i = 0; i < 11; i++)

                numeros[i] = int.Parse(
                  valor[i].ToString());


            int soma = 0;

            for (int i = 0; i < 9; i++)

                soma += (10 - i) * numeros[i];



            int resultado = soma % 11;



            if (resultado == 1 || resultado == 0)
            {

                if (numeros[9] != 0)

                    return false;

            }

            else if (numeros[9] != 11 - resultado)

                return false;



            soma = 0;

            for (int i = 0; i < 10; i++)

                soma += (11 - i) * numeros[i];



            resultado = soma % 11;



            if (resultado == 1 || resultado == 0)
            {

                if (numeros[10] != 0)

                    return false;

            }

            else

                if (numeros[10] != 11 - resultado)

                    return false;



            return true;

        }

        public static bool ValidaEmail(string email)
        {
            bool validEmail = false;
            int indexArr = email.IndexOf('@');
            if (indexArr > 0)
            {
                int indexDot = email.IndexOf('.', indexArr);
                if (indexDot - 1 > indexArr)
                {
                    if (indexDot + 1 < email.Length)
                    {
                        string indexDot2 = email.Substring(indexDot + 1, 1);
                        if (indexDot2 != ".")
                        {
                            validEmail = true;
                        }
                    }
                }
            }
            return validEmail;
        }

        #endregion

        #region Valida Inteiro/Numero/Texto
        

        public static bool ApenasInteiro(String strNumber)
        {
            if (Regex.IsMatch(strNumber,"^[0-9]{1,5}$"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool ApenasNumero(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return !objNotNumberPattern.IsMatch(strNumber) &&
            !objTwoDotPattern.IsMatch(strNumber) &&
            !objTwoMinusPattern.IsMatch(strNumber) &&
            objNumberPattern.IsMatch(strNumber);
        }

        public static bool ApenasTexto(String strToCheck)
        {
            Regex objAlphaPattern = new Regex("[^a-zA-Z]");
            return !objAlphaPattern.IsMatch(strToCheck);
        }
  
        public static bool TextoeNumero(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }

        #endregion

        #region Formatacao

        public static String FormataDataBR(String data)
        {
            DateTime dt = new DateTime();
                if (data != string.Empty)
                {
                    dt = Convert.ToDateTime(data);
                    return dt.ToShortDateString();
                }
                else
                {
                    return string.Empty;
                }
                
        }

        public static String FormataCNPJ(String cnpj)
        {
            try
            {
                // REMOVE FORMATACAO
                cnpj = cnpj.Replace(".", "");
                cnpj = cnpj.Replace("-", "");
                cnpj = cnpj.Replace("/", "");

                string CNPJFormatado = String.Format(@"{0:00\.000\.000\/0000\-00}", cnpj);
                return CNPJFormatado;
            }
            catch (Exception)
            {

                return cnpj.ToString();
            }
        }

        public static String DesformataCNPJ(String cnpj)
        {
            try
            {
                // REMOVE FORMATACAO
                cnpj = cnpj.Replace(".", "");
                cnpj = cnpj.Replace("-", "");
                cnpj = cnpj.Replace("/", "");
                
                return cnpj;
            }
            catch (Exception)
            {

                return cnpj.ToString();
            }
        }

        public static String DesformataCPF(String cpf)
        {
            try
            {
                // REMOVE FORMATACAO
                cpf = cpf.Replace(".", "");
                cpf = cpf.Replace("-", "");
                cpf = cpf.Replace("/", "");                
                return cpf;
            }
            catch (Exception)
            {

                return cpf.ToString();
            }
        }

        public static String FormataCPF(String cpf)
        {
            try
            {
                // REMOVE FORMATACAO
                cpf = cpf.Replace(".", "");
                cpf = cpf.Replace("-", "");
                cpf = cpf.Replace("/", "");          
                string CPFFormatado = String.Format(@"{0:000\.000\.000\-00}", cpf);
                return CPFFormatado;
            }
            catch (Exception)
            {

                return cpf.ToString();
            }
        }

        public static string FormataMoeda(string valor)
        {
            Double monetario = Convert.ToDouble(valor);
            return string.Format("{0:C}", monetario);
        }

        public static string FormataNumerico(string valor)
        {            
            Double numerico = Convert.ToDouble(valor);
            return string.Format("{0:N2}", numerico);

        }

        public static String FormataCEP(String cep)
        {
            try
            {
                // REMOVE FORMATACAO
                cep = cep.Replace("-", "");
                string CEPFormatado = String.Format(@"{0:000000\-00}", cep);
                return CEPFormatado;
            }
            catch (Exception)
            {

                return cep.ToString();
            }
        }

        #endregion

        #region Tratamento de Dados
   
        public static DateTime? TrataData(string data)
        {
            DateTime date = new DateTime();
            
            try
            {
                date = DateTime.Parse(data);
            }
            catch (Exception)
            {               
                return null;
            }

            return date;
        }

        public static string TrataDecimal(string valor)
        {
            Decimal temp;

            try
            {
                temp = Decimal.Parse(valor);//tenta dar o parse do tipo DECIMAL, se coseguir é valor valido

            }
            catch (Exception)
            {

                return "0";//caso ñ consiga dar o parse é porque é valor é invalido, retorna Decimal
            }

            return temp.ToString();


        }

        public static string TrataInteiro(string valor)
        {
            Int32 temp;

            try
            {
                temp = Int32.Parse(valor);//tenta dar o parse do tipo INT, se coseguir é valor valido

            }
            catch (Exception)
            {

                return "0";//caso ñ consiga dar o parse é porque é valor é invalido ou campo em branco, no db tem ser setado para ALLOW NULLS
            }

            return temp.ToString();
        }


        #endregion

        #region Formulario
        

        public static Control EncontrarControle(Control root, string id)
        {
            if (root.ID == id)
            {
                return root;
            }

            foreach (Control c in root.Controls)
            {
                Control t = EncontrarControle(c, id);
                if (t != null)
                {
                    return t;
                }
            }

            return null;
        }


        public static void DesabilitaControle(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                DesabilitaControle(c);
                if (c is DropDownList)
                {
                    ((DropDownList)(c)).Enabled = false;
                }

                if(c is TextBox)
                {
                    ((TextBox)(c)).Enabled = false;
                }
               
            }



        }

        public static void CheckBoxGridView(GridView grv, string controle, bool value)
        {
            for (int i = 0; i <= grv.Rows.Count-1 ; i++)
            {
                CheckBox chk = (CheckBox)grv.Rows[i].FindControl(controle);
                chk.Checked = value;
            }
                    
        }


        public static void ResetForms(ControlCollection ctrls)
        {
            foreach (Control ctrl in ctrls)
            {
                if (ctrl is TextBox)
                    ((TextBox)ctrl).Text = string.Empty;
                else if (ctrl is DropDownList)
                    ((DropDownList)ctrl).ClearSelection();
                else if (ctrl is CheckBox)
                    ((CheckBox)ctrl).Checked = false;
                if (ctrl.HasControls())
                    ResetForms(ctrl.Controls);
            }
        }

        #endregion


        #region GridView Retorna Valores Chaves
        

        public static String RetornaValorDataKeyGridView(GridView grd, string chave)
        {
            String key = "";
            foreach (GridViewRow row in grd.Rows)
            {
                CheckBox chk = row.FindControl("CHK_ID") as CheckBox;

                if (chk != null)
                {
                    if (chk.Checked)
                    {

                        key = grd.DataKeys[row.RowIndex][chave].ToString();
                        break;
                    }
                }

            }
            return key;
        }

        public static List<String> RetornaListaDeValoresDataKeyGridView(GridView grd, string KeyName)
        {
            String key = "";
            List<string> lista = new List<string>();
            foreach (GridViewRow row in grd.Rows)
            {
                CheckBox chk = row.FindControl("CHK_ID") as CheckBox;

                if (chk != null)
                {
                    if (chk.Checked)
                    {

                        key = grd.DataKeys[row.RowIndex][KeyName].ToString();
                        lista.Add(key);
                        
                    }
                }

            }
            return lista;
        }

        public static List<String> RetornaListaDeValoresDataKeyGridView(GridView grd, string IdCheckBox, string KeyName)
        {
            String key = "";
            List<string> lista = new List<string>();
            foreach (GridViewRow row in grd.Rows)
            {
                CheckBox chk = row.FindControl(IdCheckBox) as CheckBox;

                if (chk != null)
                {
                    if (chk.Checked)
                    {

                        key = grd.DataKeys[row.RowIndex][KeyName].ToString();
                        lista.Add(key);

                    }
                }

            }
            return lista;
        }


        #endregion

        #region SqlInjection
        private static readonly System.Text.RegularExpressions.Regex regSystemThreats =
                new System.Text.RegularExpressions.Regex(@"\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|\s?sysobjects\s?|\s?xp_.*?|\s?syslogins\s?|\s?sysremote\s?|\s?sysusers\s?|\s?sysxlogins\s?|\s?sysdatabases\s?|\s?aspnet_.*?|\s?exec\s?|",
                    System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        /// <summary>
        /// A helper method to attempt to discover known SqlInjection attacks.  
        /// For use when using one of the flexible non-parameterized access methods, such as GetPaged()
        /// </summary>
        /// <param name="whereClause">string of the whereClause to check</param>
        /// <returns>true if found, false if not found </returns>
        public static bool DetectaSqlInjection(string whereClause)
        {
            return regSystemThreats.IsMatch(whereClause);
        }

        /// <summary>
        /// A helper method to attempt to discover known SqlInjection attacks.  
        /// For use when using one of the flexible non-parameterized access methods, such as GetPaged()
        /// </summary>
        /// <param name="whereClause">string of the whereClause to check</param>
        /// <param name="orderBy">string of the orderBy clause to check</param>
        /// <returns>true if found, false if not found </returns>
        public static bool DetectaSqlInjection(string whereClause, string orderBy)
        {
            return regSystemThreats.IsMatch(whereClause) || regSystemThreats.IsMatch(orderBy);
        }
        #endregion 


        

        #region Download
		 
	
        

        /// <summary>
        /// Retorna Content Type
        /// </summary>
        /// <param name="fileExtensao"></param>
        /// <returns></returns>
        public static string RetorrnaContentType(string fileExtensao)
        {
            switch (fileExtensao)
            {
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".xls":
                    return "application/vnd.ms-excel";
                case ".xlsx":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                default:
                    return "application/octet-stream";
            }
        }

        public static void ForcaDownload(string dir_virtual, FileInfo file)
        {
            try
            {
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "ISO-8859-1";
                HttpContext.Current.Response.ContentType = RetorrnaContentType(file.Extension.ToLower());
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name.ToString());
                HttpContext.Current.Response.TransmitFile(dir_virtual + file.Name.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
                HttpContext.Current.Response.Clear();
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        #endregion

        // Exibe uma mensagem Alert
        public static void WindowOpen(string url, string nome, string altura, string largura, Page page)
        {
            // Caso haja aspas na mensagem, mudo para aspas simples
            url = url.Replace("\"", "'");
            page.ClientScript.RegisterStartupScript(typeof(string), string.Empty,
                string.Format("window.open(\"{0}\",\"{1}\" ,\"height=\"{2}\",width=\"{3}\",left=0,top=0,toolbar=no,menubar=no\");", url, nome, altura, largura), true);
        }

        public static void CacheHeader()
        {
           HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
           HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
           HttpContext.Current.Response.Cache.SetValidUntilExpires(true);
        }


        /// <summary>
        /// Retorna o endereço virtual onde esta rodando a aplicação /site
        /// </summary>
        /// <returns></returns>
        public static string PathRoot()
        {
            string url = HttpContext.Current.Request.ApplicationPath;
            return url;
        }

        public static string PathCSS(string root)
        {
            string url = string.Concat(root,"/","css");
            return url;
        }

        public static string PathScripts(string root)
        {
            string url = string.Concat(root, "/", "scripts");
            return url;
        }

        public static string PathCertificado(string root)
        {
            string url = string.Concat(root, "/", "certificado");
            return url;
        }

        public static string PathPagina(string root)
        {
            string url = string.Concat(root, "/", "pagina");
            return url;
        }

        public static string PathRelatorio(string root)
        {
            string url = string.Concat(root, "/", "relatorio");
            return url;
        }

        public static string PathJavascript(string root)
        {
            string url = string.Concat(root, "/", "js");
            return url;
        }

        public static string PathImages(string root)
        {
            string url = string.Concat(root, "/", "images");
            return url;
        }

        /// <summary>
        /// Retorna o endereço do servidor 
        /// </summary>
        /// <returns></returns>
        public static string UrlHost()
        {
            string host = HttpContext.Current.Request.Url.Host;
            return host;
        }

        /// <summary>
        /// Retorna a porta que esta rodando a aplicação
        /// </summary>
        /// <returns></returns>
        public static int UrlPorta()
        {
            int port = HttpContext.Current.Request.Url.Port;
            return port;
        }

        /// <summary>
        /// Retorna o Endereço completo que está rodando a aplicação
        /// http://www.sistema.com.br/sistema
        /// </summary>
        /// <returns></returns>
        public static string UrlAplicacao()
        {
            int port = HttpContext.Current.Request.Url.Port;
            string url = HttpContext.Current.Request.ApplicationPath;
            string host = HttpContext.Current.Request.Url.Host;
            string pag = string.Empty;
            if (port > 80)
            {
                pag = string.Format("http://" + host + ":{0}" + url, port);
            }
            else
            {
                pag = string.Format("http://" + host + url, port);
            }

            return pag;

        }

        public static Control MasterPageConteudo()
        {

            Page pg = (Page)HttpContext.Current.Handler;

            Control control = null;
            MasterPage mp = pg.Master;
            if ( mp != null)
            {
                control = PUB_FUNCOES.EncontrarControle(mp, "ConteudoPrincipal");
            }

            return control;
        }

        #region Strings
        
        public static string Left(string param, int length)
        {
            //we start at 0 since we want to get the characters starting from the
            //left and with the specified lenght and assign it to a variable
            string result = param.Substring(0, length);
            //return the result of the operation
            return result;
        }
        public static string Right(string param, int length)
        {
            //start at the index based on the lenght of the sting minus
            //the specified lenght and assign it a variable
            string result = param.Substring(param.Length - length, length);
            //return the result of the operation
            return result;
        }
        public static string Mid(string param, int startIndex, int length)
        {
            //start at the specified index in the string ang get N number of
            //characters depending on the lenght and assign it to a variable
            string result = param.Substring(startIndex, length);
            //return the result of the operation
            return result;
        }
        public static string Mid(string param, int startIndex)
        {
            //start at the specified index and return all characters after it
            //and assign it to a variable
            string result = param.Substring(startIndex);
            //return the result of the operation
            return result;
        }
        #endregion
      
    }
}
